package com.demo.socket.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * @author wangning
 * @date 2023/10/31 11:50
 */
public class UdpClient {
    // 创建一个Socket 对象来进行网络编程.
    DatagramSocket socket = null;
    String serverIP = null;
    int port = 0;

    // 通过构造方法来指定服务器的IP地址和端口号
    public UdpClient(String serverIP, int port) throws SocketException {
        socket = new DatagramSocket();
        this.serverIP = serverIP;
        this.port = port;
    }

    public void start() throws IOException {
        Scanner input = new Scanner(System.in);
        while (true) {
            System.out.println("----> ");
            // 1. 从键盘上输入请求
            String request = input.nextLine();
            // 2. 将请求打包成数据包
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(serverIP), port);
            // 3. 发送请求
            socket.send(requestPacket);
            // 4. 接收请求
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024], 1024);
            socket.receive(responsePacket);
            // 将请求转变为String 进行输出
            String response = new String(responsePacket.getData(), 0, requestPacket.getLength());
            System.out.printf("请求 : %s 响应 : %s \n", request, response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpClient udpTraClient = new UdpClient("127.0.0.1", 9090);
        udpTraClient.start();
    }
}
